package com.zoe.wan.android.example.common.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.zoe.wan.android.example.R
import com.zoe.wan.android.example.databinding.ItemKnowledgeListBinding
import com.zoe.wan.android.example.repositry.data.knowledge.KnowledgeListDataItem

class KnowledgeListAdapter : RecyclerView.Adapter<KnowledgeListAdapter.KnowledgeItemViewHolder>() {

    private var list: List<KnowledgeListDataItem?>? = null

    private var itemListener: KnowledgeCollectListener? = null

    interface KnowledgeCollectListener {
        fun itemClick(item:  KnowledgeListDataItem)

    }

    class KnowledgeItemViewHolder(var binding: ItemKnowledgeListBinding) :
        RecyclerView.ViewHolder(binding.root) {
    }

    fun registerListener(listener: KnowledgeListAdapter.KnowledgeCollectListener?) {
        this.itemListener = listener
    }

    fun setDataList(lists: List<KnowledgeListDataItem?>?) {
        lists?.let {
            list = it
            notifyDataSetChanged()
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): KnowledgeItemViewHolder {
        return KnowledgeItemViewHolder(
            DataBindingUtil.inflate(
                LayoutInflater.from(
                    parent.context,
                ),
                R.layout.item_knowledge_list,
                parent,
                false

            )
        )
    }

    override fun getItemCount(): Int {
        return list?.size ?: 0
    }

    override fun onBindViewHolder(holder: KnowledgeItemViewHolder, position: Int) {
        list?.let {

            val item = it.get(position)
            holder.binding.item = item

            var desc = ""
            item?.children?.forEach { child ->

                desc = desc + " " + child?.name
            }
            holder.binding.tvSubtitle.setText(desc)


            holder.binding.root.setOnClickListener {
                item?.let {
                    itemListener?.itemClick(it)
                }
            }
        }
    }


}